# -*- coding: utf-8 -*-
# @Date    : 2024/2/2
# @Author  : zouy
# @Email: 874112501@qq.com
"""https://www.geetest.com/demo/fullpage.html"""
import os
import random
import string
import re
import time
import json

import requests
from loguru import logger
import execjs

from util import get_track, DIR_PATH


with open(os.path.join(DIR_PATH, 'w3.js'), 'r', encoding='utf-8') as f:
    js_code = f.read()

ctx = execjs.compile(js_code)


def get_now():
    return str(int(time.time() * 1000))


def get_jsonp(text):
    jsonp_str = re.search(r"\((.*)\)", text, re.S).group(1)
    return json.loads(jsonp_str)


def get16randomStr(k):
    return ''.join(random.choices(string.digits + 'abcde', k=k))


def get_session():
    session = requests.Session()
    session.headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
        # 'Accept': '*/*',
        # 'Accept-Language': 'zh-CN,zh;q=0.9',
        # 'Cache-Control': 'no-cache',
        # 'Connection': 'keep-alive',
        # 'Pragma': 'no-cache',
        'Referer': 'https://www.geetest.com/demo/fullpage.html',
    }
    return session


def ft_register_slide(session):
    """1.1 注册获取challenge和gt"""
    url = 'https://www.geetest.com/demo/gt/register-fullpage?t={}'.format(get_now())
    res = session.get(url)
    data = res.json()
    return data['gt'], data['challenge']


def ft_get_php(session, gt, challenge, random16Key):
    """1.3 第一个w,返回c(不变)[ 12, 58, 98, 36, 43, 95, 62, 15, 12 ]和s"""
    url = 'https://apiv6.geetest.com/get.php'
    w = ctx.call('generate_w1', gt, challenge, random16Key)
    params = {
        "gt": gt,
        "challenge": challenge,
        "lang": "zh-cn",
        "pt": "0",
        "client_type": "web",
        "w": w,
        "callback": "geetest_" + get_now()
    }
    res = session.get(url, params=params)
    data = get_jsonp(res.text)

    return data


def sc_ajax(session, gt, challenge, *, c, s, random16Key):
    """2.1 第二个w，返回{"result": "slide"}
    Set-Cookie: GeeTestAjaxUser
    """
    url = "https://api.geevisit.com/ajax.php"
    track = get_track()
    w2_params = {
        'gt': gt,
        'challenge': challenge,
        'c': c,
        's': s,
        'track': track,
        'random16Key': random16Key
    }
    w = ctx.call('generate_w2', w2_params)
    params = {
        "gt": gt,
        "challenge": challenge,
        "lang": "zh-cn",
        "pt": "0",
        "client_type": "web",
        "w": w,
        "callback": "geetest_" + get_now()
    }
    headers = {
        'host': 'api.geevisit.com',
        'referer': 'https://www.geetest.com/',
    }
    res = session.get(url, params=params, headers=headers)
    data = get_jsonp(res.text)
    return data


def main():
    ss = get_session()
    random16Key = get16randomStr(16)

    gt, challenge = ft_register_slide(ss)
    # gt: e52c06c937981b90b275d0aff1d40076
    logger.info(f"1 register_slide获取gt: {gt}  challenge: {challenge}")
    time.sleep(2)

    getphp_data = ft_get_php(ss, gt=gt, challenge=challenge, random16Key=random16Key)
    c, s = getphp_data['data']['c'], getphp_data['data']['s']
    logger.info(f'2 get.php获取c: {c}   s: {s}')  # c: [12, 58, 98, 36, 43, 95, 62, 15, 12]   s: 2a6e744e
    time.sleep(2)

    # ********** 点击验证按钮  **********
    ajax_data = sc_ajax(ss, gt=gt, challenge=challenge, c=c, s=s, random16Key=random16Key)
    logger.info(f'3 ajax.php获取 {ajax_data}')  # {'status': 'success', 'data': {'result': 'slide'}}


if __name__ == '__main__':
    main()
